package cn.itcast.p2p20.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Administrator on 2016/7/29.
 */
public class FlowLayout1 extends ViewGroup {


    public FlowLayout1(Context context) {
        super(context);
    }

    public FlowLayout1(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FlowLayout1(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    //widthMeasureSpec不是控件的宽度，是控件的宽度和测量模式的组合
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        //遍历子控件进行测量
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {

            View childView = getChildAt(i);
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
        }


        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    /*

            考虑每个子控件的margin值， 每个子控件占据的宽度要加上marginLeft marginRight, 高度加上marginTop,marginBottom
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        //考虑内边距
        int startX = getPaddingLeft();
        int startY = getPaddingTop();
        int lastLineHeight = 0;
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {

            View childView = getChildAt(i);
            MarginLayoutParams layoutParams = (MarginLayoutParams) childView.getLayoutParams();
            //当子控件为GONE的时候不去显示，INVISIBLE 情况由ViewGroup已经处理
            if (childView.getVisibility() == GONE) {

                continue;
            }
            int childViewMeasuredWidth = childView.getMeasuredWidth();
            int childViewMeasuredHeight = childView.getMeasuredHeight();
            //换行，改变startX，startY
            if (startX + childViewMeasuredWidth> measuredWidth - getPaddingLeft() - getPaddingRight()) {//考虑内边距
                startX = getPaddingLeft();
                startY += lastLineHeight;
            }

            int childLeft = startX;
            int childTop = startY;
            int childRight = childLeft + childViewMeasuredWidth;
            int childBottom = childTop + childViewMeasuredHeight;
            childView.layout(childLeft, childTop, childRight, childBottom);
            //累加startX
            startX += childViewMeasuredWidth;

            //每一行所占据的高度应该是一行当中最高的
            lastLineHeight = Math.max(lastLineHeight, childViewMeasuredHeight);
        }

    }


}
